package com.lichuang.fruitvarietysm.user.listener;

import com.alibaba.fastjson.JSON;
import com.lichuang.fruitvarietysm.user.entity.User;
import com.lichuang.fruitvarietysm.user.finalproperties.EmailType;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class EmailListener {

    @Autowired
    private JavaMailSender javaMailSender;

    // 发件人邮箱地址
    @Value("${spring.mail.username}")
    private String from;

    // 发件人的姓名
    @Value("${custom.mail.fromname}")
    private String fromName;

    private String subject;


    @StreamListener("emailinput")
    public void sendEmail(Message message) throws MessagingException, IOException, TemplateException {

        // 从messageHeaders中拿到要发送邮件的类型
        String emailType = message.getHeaders().get("emailType").toString();
        if (emailType == null || emailType.equals("")) {
            return;
        }

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        // 设置发件人
        mimeMessageHelper.setFrom(fromName + "<" + from + ">");

        // 设置收件人
        User user = JSON.parseObject(message.getPayload().toString(), User.class);
        mimeMessageHelper.setTo(user.getUserEmail());

        // 加载模板
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
        configuration.setClassForTemplateLoading(this.getClass(), "/templates/email");

        // 存放向页面中传输的键值
        Map<String, Object> map = new HashMap<>();
        String html = null;

        if (EmailType.REGISTRY.equals(emailType)) {
            subject = "注册成功";
            map.put("username", user.getUserName());
            html = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("registryEmail.ftl"), map);
        } else if (EmailType.VALIDATEFORMODIFYPWD.equals(emailType)) {
            subject = "请完成邮箱验证";
            String token = message.getHeaders().get("token").toString();
            map.put("token", token);
            map.put("username", user.getUserName());
            map.put("userId", user.getUserId());
            html = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("validateEmailForModifyPwd.ftl"), map);
        } else if (EmailType.VALIDATEFORBINDEMAIL.equals(emailType)) {
            subject = "请完成邮箱验证";
            String token = message.getHeaders().get("token").toString();
            map.put("token", token);
            map.put("username", user.getUserName());
            map.put("userId", user.getUserId());
            map.put("email", user.getUserEmail());
            html = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("validateEmailForBindEmail.ftl"), map);
        }
        mimeMessageHelper.setText(html, true);
        mimeMessageHelper.setSubject(fromName + " | " + subject);
        javaMailSender.send(mimeMessage);

    }
    /**
     * 发送简单邮件
     */
//        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//        simpleMailMessage.setFrom(from);
//        simpleMailMessage.setTo(message.getPayload().toString());
//        simpleMailMessage.setSubject("这是一个主题");
//        simpleMailMessage.setText("这是文本内容");
//        javaMailSender.send(simpleMailMessage);

    /**
     * 发送带附件的邮件
     */
//        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
//        mimeMessageHelper.setFrom("薛帅航" + "<" + from + ">");
//        mimeMessageHelper.setTo(message.getPayload().toString());
//        mimeMessageHelper.setSubject("测试Springboot发送带附件的邮件");
//        // 重点，默认为false，显示原始html代码，无效果
//        mimeMessageHelper.setText("欢迎进入<a href=\"http://www.baidu.com\">百度首页</a>",true);
//        // 存放附件
//        Map<String,String> attachmentMap = new HashMap<>();
//        attachmentMap.put("附件.txt","C:\\Users\\hanghang\\Desktop\\Fruit variey Supermarket\\fruitvariety-supermarket\\user\\src\\main\\resources\\public\\file.txt");
//        attachmentMap.put("附件1.txt","C:\\Users\\hanghang\\Desktop\\Fruit variey Supermarket\\fruitvariety-supermarket\\user\\src\\main\\resources\\public\\file.txt");
//        if (attachmentMap != null){
//            attachmentMap.entrySet().stream().forEach(entrySet -> {
//                File file = new File(entrySet.getValue());
//                if (file.exists()){
//                    try {
//                        mimeMessageHelper.addAttachment(entrySet.getKey(),new FileSystemResource(file));
//                    } catch (MessagingException e) {
//                        e.printStackTrace();
//                    }
//                }
//            });
//        }
//
//        // 存放附件的重要一部
//        //mimeMessageHelper.addAttachment("附件.txt",new File("C:\\Users\\hanghang\\Desktop\\Fruit variey Supermarket\\fruitvariety-supermarket\\user\\src\\main\\resources\\public\\file.txt"));
//        javaMailSender.send(mimeMessage);

    /**
     * 发送模板邮件
     */


}
